home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2006 December / PCWDEC06.iso / Software / Trial / Paint Shop Pro XI / Data1.cab / urllib.py.0160FC08_F3D9_4869_9D41_C611C16F42D5 < prev    next >
Encoding:
Text File  |  2005-06-08  |  49.8 KB  |  1,427 lines

  1. """Open an arbitrary URL.
  2.  
  3. See the following document for more info on URLs:
  4. "Names and Addresses, URIs, URLs, URNs, URCs", at
  5. http://www.w3.org/pub/WWW/Addressing/Overview.html
  6.  
  7. See also the HTTP spec (from which the error codes are derived):
  8. "HTTP - Hypertext Transfer Protocol", at
  9. http://www.w3.org/pub/WWW/Protocols/
  10.  
  11. Related standards and specs:
  12. - RFC1808: the "relative URL" spec. (authoritative status)
  13. - RFC1738 - the "URL standard". (authoritative status)
  14. - RFC1630 - the "URI spec". (informational status)
  15.  
  16. The object returned by URLopener().open(file) will differ per
  17. protocol.  All you know is that is has methods read(), readline(),
  18. readlines(), fileno(), close() and info().  The read*(), fileno()
  19. and close() methods work like those of open files.
  20. The info() method returns a mimetools.Message object which can be
  21. used to query various info about the object, if available.
  22. (mimetools.Message objects are queried with the getheader() method.)
  23. """
  24.  
  25. import string
  26. import socket
  27. import os
  28. import time
  29. import sys
  30. from urlparse import urljoin as basejoin
  31.  
  32. __all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
  33.            "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus",
  34.            "urlencode", "url2pathname", "pathname2url", "splittag",
  35.            "localhost", "thishost", "ftperrors", "basejoin", "unwrap",
  36.            "splittype", "splithost", "splituser", "splitpasswd", "splitport",
  37.            "splitnport", "splitquery", "splitattr", "splitvalue",
  38.            "splitgophertype", "getproxies"]
  39.  
  40. __version__ = '1.16'    # XXX This version is not always updated :-(
  41.  
  42. MAXFTPCACHE = 10        # Trim the ftp cache beyond this size
  43.  
  44. # Helper for non-unix systems
  45. if os.name == 'mac':
  46.     from macurl2path import url2pathname, pathname2url
  47. elif os.name == 'nt':
  48.     from nturl2path import url2pathname, pathname2url
  49. elif os.name == 'riscos':
  50.     from rourl2path import url2pathname, pathname2url
  51. else:
  52.     def url2pathname(pathname):
  53.         return unquote(pathname)
  54.     def pathname2url(pathname):
  55.         return quote(pathname)
  56.  
  57. # This really consists of two pieces:
  58. # (1) a class which handles opening of all sorts of URLs
  59. #     (plus assorted utilities etc.)
  60. # (2) a set of functions for parsing URLs
  61. # XXX Should these be separated out into different modules?
  62.  
  63.  
  64. # Shortcut for basic usage
  65. _urlopener = None
  66. def urlopen(url, data=None, proxies=None):
  67.     """urlopen(url [, data]) -> open file-like object"""
  68.     global _urlopener
  69.     if proxies is not None:
  70.         opener = FancyURLopener(proxies=proxies)
  71.     elif not _urlopener:
  72.         opener = FancyURLopener()
  73.         _urlopener = opener
  74.     else:
  75.         opener = _urlopener
  76.     if data is None:
  77.         return opener.open(url)
  78.     else:
  79.         return opener.open(url, data)
  80. def urlretrieve(url, filename=None, reporthook=None, data=None):
  81.     global _urlopener
  82.     if not _urlopener:
  83.         _urlopener = FancyURLopener()
  84.     return _urlopener.retrieve(url, filename, reporthook, data)
  85. def urlcleanup():
  86.     if _urlopener:
  87.         _urlopener.cleanup()
  88.  
  89.  
  90. ftpcache = {}
  91. class URLopener:
  92.     """Class to open URLs.
  93.     This is a class rather than just a subroutine because we may need
  94.     more than one set of global protocol-specific options.
  95.     Note -- this is a base class for those who don't want the
  96.     automatic handling of errors type 302 (relocated) and 401
  97.     (authorization needed)."""
  98.  
  99.     __tempfiles = None
  100.  
  101.     version = "Python-urllib/%s" % __version__
  102.  
  103.     # Constructor
  104.     def __init__(self, proxies=None, **x509):
  105.         if proxies is None:
  106.             proxies = getproxies()
  107.         assert hasattr(proxies, 'has_key'), "proxies must be a mapping"
  108.         self.proxies = proxies
  109.         self.key_file = x509.get('key_file')
  110.         self.cert_file = x509.get('cert_file')
  111.         self.addheaders = [('User-agent', self.version)]
  112.         self.__tempfiles = []
  113.         self.__unlink = os.unlink # See cleanup()
  114.         self.tempcache = None
  115.         # Undocumented feature: if you assign {} to tempcache,
  116.         # it is used to cache files retrieved with
  117.         # self.retrieve().  This is not enabled by default
  118.         # since it does not work for changing documents (and I
  119.         # haven't got the logic to check expiration headers
  120.         # yet).
  121.         self.ftpcache = ftpcache
  122.         # Undocumented feature: you can use a different
  123.         # ftp cache by assigning to the .ftpcache member;
  124.         # in case you want logically independent URL openers
  125.         # XXX This is not threadsafe.  Bah.
  126.  
  127.     def __del__(self):
  128.         self.close()
  129.  
  130.     def close(self):
  131.         self.cleanup()
  132.  
  133.     def cleanup(self):
  134.         # This code sometimes runs when the rest of this module
  135.         # has already been deleted, so it can't use any globals
  136.         # or import anything.
  137.         if self.__tempfiles:
  138.             for file in self.__tempfiles:
  139.                 try:
  140.                     self.__unlink(file)
  141.                 except OSError:
  142.                     pass
  143.             del self.__tempfiles[:]
  144.         if self.tempcache:
  145.             self.tempcache.clear()
  146.  
  147.     def addheader(self, *args):
  148.         """Add a header to be used by the HTTP interface only
  149.         e.g. u.addheader('Accept', 'sound/basic')"""
  150.         self.addheaders.append(args)
  151.  
  152.     # External interface
  153.     def open(self, fullurl, data=None):
  154.         """Use URLopener().open(file) instead of open(file, 'r')."""
  155.         fullurl = unwrap(toBytes(fullurl))
  156.         if self.tempcache and fullurl in self.tempcache:
  157.             filename, headers = self.tempcache[fullurl]
  158.             fp = open(filename, 'rb')
  159.             return addinfourl(fp, headers, fullurl)
  160.         urltype, url = splittype(fullurl)
  161.         if not urltype:
  162.             urltype = 'file'
  163.         if urltype in self.proxies:
  164.             proxy = self.proxies[urltype]
  165.             urltype, proxyhost = splittype(proxy)
  166.             host, selector = splithost(proxyhost)
  167.             url = (host, fullurl) # Signal special case to open_*()
  168.         else:
  169.             proxy = None
  170.         name = 'open_' + urltype
  171.         self.type = urltype
  172.         name = name.replace('-', '_')
  173.         if not hasattr(self, name):
  174.             if proxy:
  175.                 return self.open_unknown_proxy(proxy, fullurl, data)
  176.             else:
  177.                 return self.open_unknown(fullurl, data)
  178.         try:
  179.             if data is None:
  180.                 return getattr(self, name)(url)
  181.             else:
  182.                 return getattr(self, name)(url, data)
  183.         except socket.error, msg:
  184.             raise IOError, ('socket error', msg), sys.exc_info()[2]
  185.  
  186.     def open_unknown(self, fullurl, data=None):
  187.         """Overridable interface to open unknown URL type."""
  188.         type, url = splittype(fullurl)
  189.         raise IOError, ('url error', 'unknown url type', type)
  190.  
  191.     def open_unknown_proxy(self, proxy, fullurl, data=None):
  192.         """Overridable interface to open unknown URL type."""
  193.         type, url = splittype(fullurl)
  194.         raise IOError, ('url error', 'invalid proxy for %s' % type, proxy)
  195.  
  196.     # External interface
  197.     def retrieve(self, url, filename=None, reporthook=None, data=None):
  198.         """retrieve(url) returns (filename, headers) for a local object
  199.         or (tempfilename, headers) for a remote object."""
  200.         url = unwrap(toBytes(url))
  201.         if self.tempcache and url in self.tempcache:
  202.             return self.tempcache[url]
  203.         type, url1 = splittype(url)
  204.         if filename is None and (not type or type == 'file'):
  205.             try:
  206.                 fp = self.open_local_file(url1)
  207.                 hdrs = fp.info()
  208.                 del fp
  209.                 return url2pathname(splithost(url1)[1]), hdrs
  210.             except IOError, msg:
  211.                 pass
  212.         fp = self.open(url, data)
  213.         headers = fp.info()
  214.         if filename:
  215.             tfp = open(filename, 'wb')
  216.         else:
  217.             import tempfile
  218.             garbage, path = splittype(url)
  219.             garbage, path = splithost(path or "")
  220.             path, garbage = splitquery(path or "")
  221.             path, garbage = splitattr(path or "")
  222.             suffix = os.path.splitext(path)[1]
  223.             (fd, filename) = tempfile.mkstemp(suffix)
  224.             self.__tempfiles.append(filename)
  225.             tfp = os.fdopen(fd, 'wb')
  226.         result = filename, headers
  227.         if self.tempcache is not None:
  228.             self.tempcache[url] = result
  229.         bs = 1024*8
  230.         size = -1
  231.         blocknum = 1
  232.         if reporthook:
  233.             if "content-length" in headers:
  234.                 size = int(headers["Content-Length"])
  235.             reporthook(0, bs, size)
  236.         block = fp.read(bs)
  237.         if reporthook:
  238.             reporthook(1, bs, size)
  239.         while block:
  240.             tfp.write(block)
  241.             block = fp.read(bs)
  242.             blocknum = blocknum + 1
  243.             if reporthook:
  244.                 reporthook(blocknum, bs, size)
  245.         fp.close()
  246.         tfp.close()
  247.         del fp
  248.         del tfp
  249.         return result
  250.  
  251.     # Each method named open_<type> knows how to open that type of URL
  252.  
  253.     def open_http(self, url, data=None):
  254.         """Use HTTP protocol."""
  255.         import httplib
  256.         user_passwd = None
  257.         if isinstance(url, str):
  258.             host, selector = splithost(url)
  259.             if host:
  260.                 user_passwd, host = splituser(host)
  261.                 host = unquote(host)
  262.             realhost = host
  263.         else:
  264.             host, selector = url
  265.             urltype, rest = splittype(selector)
  266.             url = rest
  267.             user_passwd = None
  268.             if urltype.lower() != 'http':
  269.                 realhost = None
  270.             else:
  271.                 realhost, rest = splithost(rest)
  272.                 if realhost:
  273.                     user_passwd, realhost = splituser(realhost)
  274.                 if user_passwd:
  275.                     selector = "%s://%s%s" % (urltype, realhost, rest)
  276.                 if proxy_bypass(realhost):
  277.                     host = realhost
  278.  
  279.             #print "proxy via http:", host, selector
  280.         if not host: raise IOError, ('http error', 'no host given')
  281.         if user_passwd:
  282.             import base64
  283.             auth = base64.encodestring(user_passwd).strip()
  284.         else:
  285.             auth = None
  286.         h = httplib.HTTP(host)
  287.         if data is not None:
  288.             h.putrequest('POST', selector)
  289.             h.putheader('Content-type', 'application/x-www-form-urlencoded')
  290.             h.putheader('Content-length', '%d' % len(data))
  291.         else:
  292.             h.putrequest('GET', selector)
  293.         if auth: h.putheader('Authorization', 'Basic %s' % auth)
  294.         if realhost: h.putheader('Host', realhost)
  295.         for args in self.addheaders: h.putheader(*args)
  296.         h.endheaders()
  297.         if data is not None:
  298.             h.send(data)
  299.         errcode, errmsg, headers = h.getreply()
  300.         fp = h.getfile()
  301.         if errcode == 200:
  302.             return addinfourl(fp, headers, "http:" + url)
  303.         else:
  304.             if data is None:
  305.                 return self.http_error(url, fp, errcode, errmsg, headers)
  306.             else:
  307.                 return self.http_error(url, fp, errcode, errmsg, headers, data)
  308.  
  309.     def http_error(self, url, fp, errcode, errmsg, headers, data=None):
  310.         """Handle http errors.
  311.         Derived class can override this, or provide specific handlers
  312.         named http_error_DDD where DDD is the 3-digit error code."""
  313.         # First check if there's a specific handler for this error
  314.         name = 'http_error_%d' % errcode
  315.         if hasattr(self, name):
  316.             method = getattr(self, name)
  317.             if data is None:
  318.                 result = method(url, fp, errcode, errmsg, headers)
  319.             else:
  320.                 result = method(url, fp, errcode, errmsg, headers, data)
  321.             if result: return result
  322.         return self.http_error_default(url, fp, errcode, errmsg, headers)
  323.  
  324.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  325.         """Default error handler: close the connection and raise IOError."""
  326.         void = fp.read()
  327.         fp.close()
  328.         raise IOError, ('http error', errcode, errmsg, headers)
  329.  
  330.     if hasattr(socket, "ssl"):
  331.         def open_https(self, url, data=None):
  332.             """Use HTTPS protocol."""
  333.             import httplib
  334.             user_passwd = None
  335.             if isinstance(url, str):
  336.                 host, selector = splithost(url)
  337.                 if host:
  338.                     user_passwd, host = splituser(host)
  339.                     host = unquote(host)
  340.                 realhost = host
  341.             else:
  342.                 host, selector = url
  343.                 urltype, rest = splittype(selector)
  344.                 url = rest
  345.                 user_passwd = None
  346.                 if urltype.lower() != 'https':
  347.                     realhost = None
  348.                 else:
  349.                     realhost, rest = splithost(rest)
  350.                     if realhost:
  351.                         user_passwd, realhost = splituser(realhost)
  352.                     if user_passwd:
  353.                         selector = "%s://%s%s" % (urltype, realhost, rest)
  354.                 #print "proxy via https:", host, selector
  355.             if not host: raise IOError, ('https error', 'no host given')
  356.             if user_passwd:
  357.                 import base64
  358.                 auth = base64.encodestring(user_passwd).strip()
  359.             else:
  360.                 auth = None
  361.             h = httplib.HTTPS(host, 0,
  362.                               key_file=self.key_file,
  363.                               cert_file=self.cert_file)
  364.             if data is not None:
  365.                 h.putrequest('POST', selector)
  366.                 h.putheader('Content-type',
  367.                             'application/x-www-form-urlencoded')
  368.                 h.putheader('Content-length', '%d' % len(data))
  369.             else:
  370.                 h.putrequest('GET', selector)
  371.             if auth: h.putheader('Authorization', 'Basic %s' % auth)
  372.             if realhost: h.putheader('Host', realhost)
  373.             for args in self.addheaders: h.putheader(*args)
  374.             h.endheaders()
  375.             if data is not None:
  376.                 h.send(data)
  377.             errcode, errmsg, headers = h.getreply()
  378.             fp = h.getfile()
  379.             if errcode == 200:
  380.                 return addinfourl(fp, headers, "https:" + url)
  381.             else:
  382.                 if data is None:
  383.                     return self.http_error(url, fp, errcode, errmsg, headers)
  384.                 else:
  385.                     return self.http_error(url, fp, errcode, errmsg, headers,
  386.                                            data)
  387.  
  388.     def open_gopher(self, url):
  389.         """Use Gopher protocol."""
  390.         import gopherlib
  391.         host, selector = splithost(url)
  392.         if not host: raise IOError, ('gopher error', 'no host given')
  393.         host = unquote(host)
  394.         type, selector = splitgophertype(selector)
  395.         selector, query = splitquery(selector)
  396.         selector = unquote(selector)
  397.         if query:
  398.             query = unquote(query)
  399.             fp = gopherlib.send_query(selector, query, host)
  400.         else:
  401.             fp = gopherlib.send_selector(selector, host)
  402.         return addinfourl(fp, noheaders(), "gopher:" + url)
  403.  
  404.     def open_file(self, url):
  405.         """Use local file or FTP depending on form of URL."""
  406.         if url[:2] == '//' and url[2:3] != '/' and url[2:12].lower() != 'localhost/':
  407.             return self.open_ftp(url)
  408.         else:
  409.             return self.open_local_file(url)
  410.  
  411.     def open_local_file(self, url):
  412.         """Use local file."""
  413.         import mimetypes, mimetools, email.Utils, StringIO
  414.         host, file = splithost(url)
  415.         localname = url2pathname(file)
  416.         try:
  417.             stats = os.stat(localname)
  418.         except OSError, e:
  419.             raise IOError(e.errno, e.strerror, e.filename)
  420.         size = stats.st_size
  421.         modified = email.Utils.formatdate(stats.st_mtime, usegmt=True)
  422.         mtype = mimetypes.guess_type(url)[0]
  423.         headers = mimetools.Message(StringIO.StringIO(
  424.             'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
  425.             (mtype or 'text/plain', size, modified)))
  426.         if not host:
  427.             urlfile = file
  428.             if file[:1] == '/':
  429.                 urlfile = 'file://' + file
  430.             return addinfourl(open(localname, 'rb'),
  431.                               headers, urlfile)
  432.         host, port = splitport(host)
  433.         if not port \
  434.            and socket.gethostbyname(host) in (localhost(), thishost()):
  435.             urlfile = file
  436.             if file[:1] == '/':
  437.                 urlfile = 'file://' + file
  438.             return addinfourl(open(localname, 'rb'),
  439.                               headers, urlfile)
  440.         raise IOError, ('local file error', 'not on local host')
  441.  
  442.     def open_ftp(self, url):
  443.         """Use FTP protocol."""
  444.         import mimetypes, mimetools, StringIO
  445.         host, path = splithost(url)
  446.         if not host: raise IOError, ('ftp error', 'no host given')
  447.         host, port = splitport(host)
  448.         user, host = splituser(host)
  449.         if user: user, passwd = splitpasswd(user)
  450.         else: passwd = None
  451.         host = unquote(host)
  452.         user = unquote(user or '')
  453.         passwd = unquote(passwd or '')
  454.         host = socket.gethostbyname(host)
  455.         if not port:
  456.             import ftplib
  457.             port = ftplib.FTP_PORT
  458.         else:
  459.             port = int(port)
  460.         path, attrs = splitattr(path)
  461.         path = unquote(path)
  462.         dirs = path.split('/')
  463.         dirs, file = dirs[:-1], dirs[-1]
  464.         if dirs and not dirs[0]: dirs = dirs[1:]
  465.         if dirs and not dirs[0]: dirs[0] = '/'
  466.         key = user, host, port, '/'.join(dirs)
  467.         # XXX thread unsafe!
  468.         if len(self.ftpcache) > MAXFTPCACHE:
  469.             # Prune the cache, rather arbitrarily
  470.             for k in self.ftpcache.keys():
  471.                 if k != key:
  472.                     v = self.ftpcache[k]
  473.                     del self.ftpcache[k]
  474.                     v.close()
  475.         try:
  476.             if not key in self.ftpcache:
  477.                 self.ftpcache[key] = \
  478.                     ftpwrapper(user, passwd, host, port, dirs)
  479.             if not file: type = 'D'
  480.             else: type = 'I'
  481.             for attr in attrs:
  482.                 attr, value = splitvalue(attr)
  483.                 if attr.lower() == 'type' and \
  484.                    value in ('a', 'A', 'i', 'I', 'd', 'D'):
  485.                     type = value.upper()
  486.             (fp, retrlen) = self.ftpcache[key].retrfile(file, type)
  487.             mtype = mimetypes.guess_type("ftp:" + url)[0]
  488.             headers = ""
  489.             if mtype:
  490.                 headers += "Content-Type: %s\n" % mtype
  491.             if retrlen is not None and retrlen >= 0:
  492.                 headers += "Content-Length: %d\n" % retrlen
  493.             headers = mimetools.Message(StringIO.StringIO(headers))
  494.             return addinfourl(fp, headers, "ftp:" + url)
  495.         except ftperrors(), msg:
  496.             raise IOError, ('ftp error', msg), sys.exc_info()[2]
  497.  
  498.     def open_data(self, url, data=None):
  499.         """Use "data" URL."""
  500.         # ignore POSTed data
  501.         #
  502.         # syntax of data URLs:
  503.         # dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
  504.         # mediatype := [ type "/" subtype ] *( ";" parameter )
  505.         # data      := *urlchar
  506.         # parameter := attribute "=" value
  507.         import StringIO, mimetools
  508.         try:
  509.             [type, data] = url.split(',', 1)
  510.         except ValueError:
  511.             raise IOError, ('data error', 'bad data URL')
  512.         if not type:
  513.             type = 'text/plain;charset=US-ASCII'
  514.         semi = type.rfind(';')
  515.         if semi >= 0 and '=' not in type[semi:]:
  516.             encoding = type[semi+1:]
  517.             type = type[:semi]
  518.         else:
  519.             encoding = ''
  520.         msg = []
  521.         msg.append('Date: %s'%time.strftime('%a, %d %b %Y %T GMT',
  522.                                             time.gmtime(time.time())))
  523.         msg.append('Content-type: %s' % type)
  524.         if encoding == 'base64':
  525.             import base64
  526.             data = base64.decodestring(data)
  527.         else:
  528.             data = unquote(data)
  529.         msg.append('Content-length: %d' % len(data))
  530.         msg.append('')
  531.         msg.append(data)
  532.         msg = '\n'.join(msg)
  533.         f = StringIO.StringIO(msg)
  534.         headers = mimetools.Message(f, 0)
  535.         f.fileno = None     # needed for addinfourl
  536.         return addinfourl(f, headers, url)
  537.  
  538.  
  539. class FancyURLopener(URLopener):
  540.     """Derived class with handlers for errors we can handle (perhaps)."""
  541.  
  542.     def __init__(self, *args, **kwargs):
  543.         URLopener.__init__(self, *args, **kwargs)
  544.         self.auth_cache = {}
  545.         self.tries = 0
  546.         self.maxtries = 10
  547.  
  548.     def http_error_default(self, url, fp, errcode, errmsg, headers):
  549.         """Default error handling -- don't raise an exception."""
  550.         return addinfourl(fp, headers, "http:" + url)
  551.  
  552.     def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
  553.         """Error 302 -- relocated (temporarily)."""
  554.         self.tries += 1
  555.         if self.maxtries and self.tries >= self.maxtries:
  556.             if hasattr(self, "http_error_500"):
  557.                 meth = self.http_error_500
  558.             else:
  559.                 meth = self.http_error_default
  560.             self.tries = 0
  561.             return meth(url, fp, 500,
  562.                         "Internal Server Error: Redirect Recursion", headers)
  563.         result = self.redirect_internal(url, fp, errcode, errmsg, headers,
  564.                                         data)
  565.         self.tries = 0
  566.         return result
  567.  
  568.     def redirect_internal(self, url, fp, errcode, errmsg, headers, data):
  569.         if 'location' in headers:
  570.             newurl = headers['location']
  571.         elif 'uri' in headers:
  572.             newurl = headers['uri']
  573.         else:
  574.             return
  575.         void = fp.read()
  576.         fp.close()
  577.         # In case the server sent a relative URL, join with original:
  578.         newurl = basejoin(self.type + ":" + url, newurl)
  579.         return self.open(newurl)
  580.  
  581.     def http_error_301(self, url, fp, errcode, errmsg, headers, data=None):
  582.         """Error 301 -- also relocated (permanently)."""
  583.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  584.  
  585.     def http_error_303(self, url, fp, errcode, errmsg, headers, data=None):
  586.         """Error 303 -- also relocated (essentially identical to 302)."""
  587.         return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  588.  
  589.     def http_error_307(self, url, fp, errcode, errmsg, headers, data=None):
  590.         """Error 307 -- relocated, but turn POST into error."""
  591.         if data is None:
  592.             return self.http_error_302(url, fp, errcode, errmsg, headers, data)
  593.         else:
  594.             return self.http_error_default(url, fp, errcode, errmsg, headers)
  595.  
  596.     def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
  597.         """Error 401 -- authentication required.
  598.         See this URL for a description of the basic authentication scheme:
  599.         http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt"""
  600.         if not 'www-authenticate' in headers:
  601.             URLopener.http_error_default(self, url, fp,
  602.                                          errcode, errmsg, headers)
  603.         stuff = headers['www-authenticate']
  604.         import re
  605.         match = re.match('[ \t]*([^ \t]+)[ \t]+realm="([^"]*)"', stuff)
  606.         if not match:
  607.             URLopener.http_error_default(self, url, fp,
  608.                                          errcode, errmsg, headers)
  609.         scheme, realm = match.groups()
  610.         if scheme.lower() != 'basic':
  611.             URLopener.http_error_default(self, url, fp,
  612.                                          errcode, errmsg, headers)
  613.         name = 'retry_' + self.type + '_basic_auth'
  614.         if data is None:
  615.             return getattr(self,name)(url, realm)
  616.         else:
  617.             return getattr(self,name)(url, realm, data)
  618.  
  619.     def retry_http_basic_auth(self, url, realm, data=None):
  620.         host, selector = splithost(url)
  621.         i = host.find('@') + 1
  622.         host = host[i:]
  623.         user, passwd = self.get_user_passwd(host, realm, i)
  624.         if not (user or passwd): return None
  625.         host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
  626.         newurl = 'http://' + host + selector
  627.         if data is None:
  628.             return self.open(newurl)
  629.         else:
  630.             return self.open(newurl, data)
  631.  
  632.     def retry_https_basic_auth(self, url, realm, data=None):
  633.         host, selector = splithost(url)
  634.         i = host.find('@') + 1
  635.         host = host[i:]
  636.         user, passwd = self.get_user_passwd(host, realm, i)
  637.         if not (user or passwd): return None
  638.         host = quote(user, safe='') + ':' + quote(passwd, safe='') + '@' + host
  639.         newurl = '//' + host + selector
  640.         return self.open_https(newurl, data)
  641.  
  642.     def get_user_passwd(self, host, realm, clear_cache = 0):
  643.         key = realm + '@' + host.lower()
  644.         if key in self.auth_cache:
  645.             if clear_cache:
  646.                 del self.auth_cache[key]
  647.             else:
  648.                 return self.auth_cache[key]
  649.         user, passwd = self.prompt_user_passwd(host, realm)
  650.         if user or passwd: self.auth_cache[key] = (user, passwd)
  651.         return user, passwd
  652.  
  653.     def prompt_user_passwd(self, host, realm):
  654.         """Override this in a GUI environment!"""
  655.         import getpass
  656.         try:
  657.             user = raw_input("Enter username for %s at %s: " % (realm,
  658.                                                                 host))
  659.             passwd = getpass.getpass("Enter password for %s in %s at %s: " %
  660.                 (user, realm, host))
  661.             return user, passwd
  662.         except KeyboardInterrupt:
  663.             print
  664.             return None, None
  665.  
  666.  
  667. # Utility functions
  668.  
  669. _localhost = None
  670. def localhost():
  671.     """Return the IP address of the magic hostname 'localhost'."""
  672.     global _localhost
  673.     if _localhost is None:
  674.         _localhost = socket.gethostbyname('localhost')
  675.     return _localhost
  676.  
  677. _thishost = None
  678. def thishost():
  679.     """Return the IP address of the current host."""
  680.     global _thishost
  681.     if _thishost is None:
  682.         _thishost = socket.gethostbyname(socket.gethostname())
  683.     return _thishost
  684.  
  685. _ftperrors = None
  686. def ftperrors():
  687.     """Return the set of errors raised by the FTP class."""
  688.     global _ftperrors
  689.     if _ftperrors is None:
  690.         import ftplib
  691.         _ftperrors = ftplib.all_errors
  692.     return _ftperrors
  693.  
  694. _noheaders = None
  695. def noheaders():
  696.     """Return an empty mimetools.Message object."""
  697.     global _noheaders
  698.     if _noheaders is None:
  699.         import mimetools
  700.         import StringIO
  701.         _noheaders = mimetools.Message(StringIO.StringIO(), 0)
  702.         _noheaders.fp.close()   # Recycle file descriptor
  703.     return _noheaders
  704.  
  705.  
  706. # Utility classes
  707.  
  708. class ftpwrapper:
  709.     """Class used by open_ftp() for cache of open FTP connections."""
  710.  
  711.     def __init__(self, user, passwd, host, port, dirs):
  712.         self.user = user
  713.         self.passwd = passwd
  714.         self.host = host
  715.         self.port = port
  716.         self.dirs = dirs
  717.         self.init()
  718.  
  719.     def init(self):
  720.         import ftplib
  721.         self.busy = 0
  722.         self.ftp = ftplib.FTP()
  723.         self.ftp.connect(self.host, self.port)
  724.         self.ftp.login(self.user, self.passwd)
  725.         for dir in self.dirs:
  726.             self.ftp.cwd(dir)
  727.  
  728.     def retrfile(self, file, type):
  729.         import ftplib
  730.         self.endtransfer()
  731.         if type in ('d', 'D'): cmd = 'TYPE A'; isdir = 1
  732.         else: cmd = 'TYPE ' + type; isdir = 0
  733.         try:
  734.             self.ftp.voidcmd(cmd)
  735.         except ftplib.all_errors:
  736.             self.init()
  737.             self.ftp.voidcmd(cmd)
  738.         conn = None
  739.         if file and not isdir:
  740.             # Use nlst to see if the file exists at all
  741.             try:
  742.                 self.ftp.nlst(file)
  743.             except ftplib.error_perm, reason:
  744.                 raise IOError, ('ftp error', reason), sys.exc_info()[2]
  745.             # Restore the transfer mode!
  746.             self.ftp.voidcmd(cmd)
  747.             # Try to retrieve as a file
  748.             try:
  749.                 cmd = 'RETR ' + file
  750.                 conn = self.ftp.ntransfercmd(cmd)
  751.             except ftplib.error_perm, reason:
  752.                 if str(reason)[:3] != '550':
  753.                     raise IOError, ('ftp error', reason), sys.exc_info()[2]
  754.         if not conn:
  755.             # Set transfer mode to ASCII!
  756.             self.ftp.voidcmd('TYPE A')
  757.             # Try a directory listing
  758.             if file: cmd = 'LIST ' + file
  759.             else: cmd = 'LIST'
  760.             conn = self.ftp.ntransfercmd(cmd)
  761.         self.busy = 1
  762.         # Pass back both a suitably decorated object and a retrieval length
  763.         return (addclosehook(conn[0].makefile('rb'),
  764.                              self.endtransfer), conn[1])
  765.     def endtransfer(self):
  766.         if not self.busy:
  767.             return
  768.         self.busy = 0
  769.         try:
  770.             self.ftp.voidresp()
  771.         except ftperrors():
  772.             pass
  773.  
  774.     def close(self):
  775.         self.endtransfer()
  776.         try:
  777.             self.ftp.close()
  778.         except ftperrors():
  779.             pass
  780.  
  781. class addbase:
  782.     """Base class for addinfo and addclosehook."""
  783.  
  784.     def __init__(self, fp):
  785.         self.fp = fp
  786.         self.read = self.fp.read
  787.         self.readline = self.fp.readline
  788.         if hasattr(self.fp, "readlines"): self.readlines = self.fp.readlines
  789.         if hasattr(self.fp, "fileno"): self.fileno = self.fp.fileno
  790.         if hasattr(self.fp, "__iter__"):
  791.             self.__iter__ = self.fp.__iter__
  792.             if hasattr(self.fp, "next"):
  793.                 self.next = self.fp.next
  794.  
  795.     def __repr__(self):
  796.         return '<%s at %r whose fp = %r>' % (self.__class__.__name__,
  797.                                              id(self), self.fp)
  798.  
  799.     def close(self):
  800.         self.read = None
  801.         self.readline = None
  802.         self.readlines = None
  803.         self.fileno = None
  804.         if self.fp: self.fp.close()
  805.         self.fp = None
  806.  
  807. class addclosehook(addbase):
  808.     """Class to add a close hook to an open file."""
  809.  
  810.     def __init__(self, fp, closehook, *hookargs):
  811.         addbase.__init__(self, fp)
  812.         self.closehook = closehook
  813.         self.hookargs = hookargs
  814.  
  815.     def close(self):
  816.         addbase.close(self)
  817.         if self.closehook:
  818.             self.closehook(*self.hookargs)
  819.             self.closehook = None
  820.             self.hookargs = None
  821.  
  822. class addinfo(addbase):
  823.     """class to add an info() method to an open file."""
  824.  
  825.     def __init__(self, fp, headers):
  826.         addbase.__init__(self, fp)
  827.         self.headers = headers
  828.  
  829.     def info(self):
  830.         return self.headers
  831.  
  832. class addinfourl(addbase):
  833.     """class to add info() and geturl() methods to an open file."""
  834.  
  835.     def __init__(self, fp, headers, url):
  836.         addbase.__init__(self, fp)
  837.         self.headers = headers
  838.         self.url = url
  839.  
  840.     def info(self):
  841.         return self.headers
  842.  
  843.     def geturl(self):
  844.         return self.url
  845.  
  846.  
  847. # Utilities to parse URLs (most of these return None for missing parts):
  848. # unwrap('<URL:type://host/path>') --> 'type://host/path'
  849. # splittype('type:opaquestring') --> 'type', 'opaquestring'
  850. # splithost('//host[:port]/path') --> 'host[:port]', '/path'
  851. # splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'
  852. # splitpasswd('user:passwd') -> 'user', 'passwd'
  853. # splitport('host:port') --> 'host', 'port'
  854. # splitquery('/path?query') --> '/path', 'query'
  855. # splittag('/path#tag') --> '/path', 'tag'
  856. # splitattr('/path;attr1=value1;attr2=value2;...') ->
  857. #   '/path', ['attr1=value1', 'attr2=value2', ...]
  858. # splitvalue('attr=value') --> 'attr', 'value'
  859. # splitgophertype('/Xselector') --> 'X', 'selector'
  860. # unquote('abc%20def') -> 'abc def'
  861. # quote('abc def') -> 'abc%20def')
  862.  
  863. try:
  864.     unicode
  865. except NameError:
  866.     def _is_unicode(x):
  867.         return 0
  868. else:
  869.     def _is_unicode(x):
  870.         return isinstance(x, unicode)
  871.  
  872. def toBytes(url):
  873.     """toBytes(u"URL") --> 'URL'."""
  874.     # Most URL schemes require ASCII. If that changes, the conversion
  875.     # can be relaxed
  876.     if _is_unicode(url):
  877.         try:
  878.             url = url.encode("ASCII")
  879.         except UnicodeError:
  880.             raise UnicodeError("URL " + repr(url) +
  881.                                " contains non-ASCII characters")
  882.     return url
  883.  
  884. def unwrap(url):
  885.     """unwrap('<URL:type://host/path>') --> 'type://host/path'."""
  886.     url = url.strip()
  887.     if url[:1] == '<' and url[-1:] == '>':
  888.         url = url[1:-1].strip()
  889.     if url[:4] == 'URL:': url = url[4:].strip()
  890.     return url
  891.  
  892. _typeprog = None
  893. def splittype(url):
  894.     """splittype('type:opaquestring') --> 'type', 'opaquestring'."""
  895.     global _typeprog
  896.     if _typeprog is None:
  897.         import re
  898.         _typeprog = re.compile('^([^/:]+):')
  899.  
  900.     match = _typeprog.match(url)
  901.     if match:
  902.         scheme = match.group(1)
  903.         return scheme.lower(), url[len(scheme) + 1:]
  904.     return None, url
  905.  
  906. _hostprog = None
  907. def splithost(url):
  908.     """splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
  909.     global _hostprog
  910.     if _hostprog is None:
  911.         import re
  912.         _hostprog = re.compile('^//([^/]*)(.*)$')
  913.  
  914.     match = _hostprog.match(url)
  915.     if match: return match.group(1, 2)
  916.     return None, url
  917.  
  918. _userprog = None
  919. def splituser(host):
  920.     """splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
  921.     global _userprog
  922.     if _userprog is None:
  923.         import re
  924.         _userprog = re.compile('^(.*)@(.*)$')
  925.  
  926.     match = _userprog.match(host)
  927.     if match: return map(unquote, match.group(1, 2))
  928.     return None, host
  929.  
  930. _passwdprog = None
  931. def splitpasswd(user):
  932.     """splitpasswd('user:passwd') -> 'user', 'passwd'."""
  933.     global _passwdprog
  934.     if _passwdprog is None:
  935.         import re
  936.         _passwdprog = re.compile('^([^:]*):(.*)$')
  937.  
  938.     match = _passwdprog.match(user)
  939.     if match: return match.group(1, 2)
  940.     return user, None
  941.  
  942. # splittag('/path#tag') --> '/path', 'tag'
  943. _portprog = None
  944. def splitport(host):
  945.     """splitport('host:port') --> 'host', 'port'."""
  946.     global _portprog
  947.     if _portprog is None:
  948.         import re
  949.         _portprog = re.compile('^(.*):([0-9]+)$')
  950.  
  951.     match = _portprog.match(host)
  952.     if match: return match.group(1, 2)
  953.     return host, None
  954.  
  955. _nportprog = None
  956. def splitnport(host, defport=-1):
  957.     """Split host and port, returning numeric port.
  958.     Return given default port if no ':' found; defaults to -1.
  959.     Return numerical port if a valid number are found after ':'.
  960.     Return None if ':' but not a valid number."""
  961.     global _nportprog
  962.     if _nportprog is None:
  963.         import re
  964.         _nportprog = re.compile('^(.*):(.*)$')
  965.  
  966.     match = _nportprog.match(host)
  967.     if match:
  968.         host, port = match.group(1, 2)
  969.         try:
  970.             if not port: raise ValueError, "no digits"
  971.             nport = int(port)
  972.         except ValueError:
  973.             nport = None
  974.         return host, nport
  975.     return host, defport
  976.  
  977. _queryprog = None
  978. def splitquery(url):
  979.     """splitquery('/path?query') --> '/path', 'query'."""
  980.     global _queryprog
  981.     if _queryprog is None:
  982.         import re
  983.         _queryprog = re.compile('^(.*)\?([^?]*)$')
  984.  
  985.     match = _queryprog.match(url)
  986.     if match: return match.group(1, 2)
  987.     return url, None
  988.  
  989. _tagprog = None
  990. def splittag(url):
  991.     """splittag('/path#tag') --> '/path', 'tag'."""
  992.     global _tagprog
  993.     if _tagprog is None:
  994.         import re
  995.         _tagprog = re.compile('^(.*)#([^#]*)$')
  996.  
  997.     match = _tagprog.match(url)
  998.     if match: return match.group(1, 2)
  999.     return url, None
  1000.  
  1001. def splitattr(url):
  1002.     """splitattr('/path;attr1=value1;attr2=value2;...') ->
  1003.         '/path', ['attr1=value1', 'attr2=value2', ...]."""
  1004.     words = url.split(';')
  1005.     return words[0], words[1:]
  1006.  
  1007. _valueprog = None
  1008. def splitvalue(attr):
  1009.     """splitvalue('attr=value') --> 'attr', 'value'."""
  1010.     global _valueprog
  1011.     if _valueprog is None:
  1012.         import re
  1013.         _valueprog = re.compile('^([^=]*)=(.*)$')
  1014.  
  1015.     match = _valueprog.match(attr)
  1016.     if match: return match.group(1, 2)
  1017.     return attr, None
  1018.  
  1019. def splitgophertype(selector):
  1020.     """splitgophertype('/Xselector') --> 'X', 'selector'."""
  1021.     if selector[:1] == '/' and selector[1:2]:
  1022.         return selector[1], selector[2:]
  1023.     return None, selector
  1024.  
  1025. def unquote(s):
  1026.     """unquote('abc%20def') -> 'abc def'."""
  1027.     mychr = chr
  1028.     myatoi = int
  1029.     list = s.split('%')
  1030.     res = [list[0]]
  1031.     myappend = res.append
  1032.     del list[0]
  1033.     for item in list:
  1034.         if item[1:2]:
  1035.             try:
  1036.                 myappend(mychr(myatoi(item[:2], 16))
  1037.                      + item[2:])
  1038.             except ValueError:
  1039.                 myappend('%' + item)
  1040.         else:
  1041.             myappend('%' + item)
  1042.     return "".join(res)
  1043.  
  1044. def unquote_plus(s):
  1045.     """unquote('%7e/abc+def') -> '~/abc def'"""
  1046.     s = s.replace('+', ' ')
  1047.     return unquote(s)
  1048.  
  1049. always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  1050.                'abcdefghijklmnopqrstuvwxyz'
  1051.                '0123456789' '_.-')
  1052.  
  1053. _fast_safe_test = always_safe + '/'
  1054. _fast_safe = None
  1055.  
  1056. def _fast_quote(s):
  1057.     global _fast_safe
  1058.     if _fast_safe is None:
  1059.         _fast_safe = {}
  1060.         for c in _fast_safe_test:
  1061.             _fast_safe[c] = c
  1062.     res = list(s)
  1063.     for i in range(len(res)):
  1064.         c = res[i]
  1065.         if not c in _fast_safe:
  1066.             res[i] = '%%%02X' % ord(c)
  1067.     return ''.join(res)
  1068.  
  1069. def quote(s, safe = '/'):
  1070.     """quote('abc def') -> 'abc%20def'
  1071.  
  1072.     Each part of a URL, e.g. the path info, the query, etc., has a
  1073.     different set of reserved characters that must be quoted.
  1074.  
  1075.     RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
  1076.     the following reserved characters.
  1077.  
  1078.     reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
  1079.                   "$" | ","
  1080.  
  1081.     Each of these characters is reserved in some component of a URL,
  1082.     but not necessarily in all of them.
  1083.  
  1084.     By default, the quote function is intended for quoting the path
  1085.     section of a URL.  Thus, it will not encode '/'.  This character
  1086.     is reserved, but in typical usage the quote function is being
  1087.     called on a path where the existing slash characters are used as
  1088.     reserved characters.
  1089.     """
  1090.     safe = always_safe + safe
  1091.     if _fast_safe_test == safe:
  1092.         return _fast_quote(s)
  1093.     res = list(s)
  1094.     for i in range(len(res)):
  1095.         c = res[i]
  1096.         if c not in safe:
  1097.             res[i] = '%%%02X' % ord(c)
  1098.     return ''.join(res)
  1099.  
  1100. def quote_plus(s, safe = ''):
  1101.     """Quote the query fragment of a URL; replacing ' ' with '+'"""
  1102.     if ' ' in s:
  1103.         l = s.split(' ')
  1104.         for i in range(len(l)):
  1105.             l[i] = quote(l[i], safe)
  1106.         return '+'.join(l)
  1107.     else:
  1108.         return quote(s, safe)
  1109.  
  1110. def urlencode(query,doseq=0):
  1111.     """Encode a sequence of two-element tuples or dictionary into a URL query string.
  1112.  
  1113.     If any values in the query arg are sequences and doseq is true, each
  1114.     sequence element is converted to a separate parameter.
  1115.  
  1116.     If the query arg is a sequence of two-element tuples, the order of the
  1117.     parameters in the output will match the order of parameters in the
  1118.     input.
  1119.     """
  1120.  
  1121.     if hasattr(query,"items"):
  1122.         # mapping objects
  1123.         query = query.items()
  1124.     else:
  1125.         # it's a bother at times that strings and string-like objects are
  1126.         # sequences...
  1127.         try:
  1128.             # non-sequence items should not work with len()
  1129.             # non-empty strings will fail this
  1130.             if len(query) and not isinstance(query[0], tuple):
  1131.                 raise TypeError
  1132.             # zero-length sequences of all types will get here and succeed,
  1133.             # but that's a minor nit - since the original implementation
  1134.             # allowed empty dicts that type of behavior probably should be
  1135.             # preserved for consistency
  1136.         except TypeError:
  1137.             ty,va,tb = sys.exc_info()
  1138.             raise TypeError, "not a valid non-string sequence or mapping object", tb
  1139.  
  1140.     l = []
  1141.     if not doseq:
  1142.         # preserve old behavior
  1143.         for k, v in query:
  1144.             k = quote_plus(str(k))
  1145.             v = quote_plus(str(v))
  1146.             l.append(k + '=' + v)
  1147.     else:
  1148.         for k, v in query:
  1149.             k = quote_plus(str(k))
  1150.             if isinstance(v, str):
  1151.                 v = quote_plus(v)
  1152.                 l.append(k + '=' + v)
  1153.             elif _is_unicode(v):
  1154.                 # is there a reasonable way to convert to ASCII?
  1155.                 # encode generates a string, but "replace" or "ignore"
  1156.                 # lose information and "strict" can raise UnicodeError
  1157.                 v = quote_plus(v.encode("ASCII","replace"))
  1158.                 l.append(k + '=' + v)
  1159.             else:
  1160.                 try:
  1161.                     # is this a sufficient test for sequence-ness?
  1162.                     x = len(v)
  1163.                 except TypeError:
  1164.                     # not a sequence
  1165.                     v = quote_plus(str(v))
  1166.                     l.append(k + '=' + v)
  1167.                 else:
  1168.                     # loop over the sequence
  1169.                     for elt in v:
  1170.                         l.append(k + '=' + quote_plus(str(elt)))
  1171.     return '&'.join(l)
  1172.  
  1173. # Proxy handling
  1174. def getproxies_environment():
  1175.     """Return a dictionary of scheme -> proxy server URL mappings.
  1176.  
  1177.     Scan the environment for variables named <scheme>_proxy;
  1178.     this seems to be the standard convention.  If you need a
  1179.     different way, you can pass a proxies dictionary to the
  1180.     [Fancy]URLopener constructor.
  1181.  
  1182.     """
  1183.     proxies = {}
  1184.     for name, value in os.environ.items():
  1185.         name = name.lower()
  1186.         if value and name[-6:] == '_proxy':
  1187.             proxies[name[:-6]] = value
  1188.     return proxies
  1189.  
  1190. if sys.platform == 'darwin':
  1191.     def getproxies_internetconfig():
  1192.         """Return a dictionary of scheme -> proxy server URL mappings.
  1193.  
  1194.         By convention the mac uses Internet Config to store
  1195.         proxies.  An HTTP proxy, for instance, is stored under
  1196.         the HttpProxy key.
  1197.  
  1198.         """
  1199.         try:
  1200.             import ic
  1201.         except ImportError:
  1202.             return {}
  1203.  
  1204.         try:
  1205.             config = ic.IC()
  1206.         except ic.error:
  1207.             return {}
  1208.         proxies = {}
  1209.         # HTTP:
  1210.         if 'UseHTTPProxy' in config and config['UseHTTPProxy']:
  1211.             try:
  1212.                 value = config['HTTPProxyHost']
  1213.             except ic.error:
  1214.                 pass
  1215.             else:
  1216.                 proxies['http'] = 'http://%s' % value
  1217.         # FTP: XXXX To be done.
  1218.         # Gopher: XXXX To be done.
  1219.         return proxies
  1220.  
  1221.     def proxy_bypass(x):
  1222.         return 0
  1223.  
  1224.     def getproxies():
  1225.         return getproxies_environment() or getproxies_internetconfig()
  1226.  
  1227. elif os.name == 'nt':
  1228.     def getproxies_registry():
  1229.         """Return a dictionary of scheme -> proxy server URL mappings.
  1230.  
  1231.         Win32 uses the registry to store proxies.
  1232.  
  1233.         """
  1234.         proxies = {}
  1235.         try:
  1236.             import _winreg
  1237.         except ImportError:
  1238.             # Std module, so should be around - but you never know!
  1239.             return proxies
  1240.         try:
  1241.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
  1242.                 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
  1243.             proxyEnable = _winreg.QueryValueEx(internetSettings,
  1244.                                                'ProxyEnable')[0]
  1245.             if proxyEnable:
  1246.                 # Returned as Unicode but problems if not converted to ASCII
  1247.                 proxyServer = str(_winreg.QueryValueEx(internetSettings,
  1248.                                                        'ProxyServer')[0])
  1249.                 if '=' in proxyServer:
  1250.                     # Per-protocol settings
  1251.                     for p in proxyServer.split(';'):
  1252.                         protocol, address = p.split('=', 1)
  1253.                         # See if address has a type:// prefix
  1254.                         import re
  1255.                         if not re.match('^([^/:]+)://', address):
  1256.                             address = '%s://%s' % (protocol, address)
  1257.                         proxies[protocol] = address
  1258.                 else:
  1259.                     # Use one setting for all protocols
  1260.                     if proxyServer[:5] == 'http:':
  1261.                         proxies['http'] = proxyServer
  1262.                     else:
  1263.                         proxies['http'] = 'http://%s' % proxyServer
  1264.                         proxies['ftp'] = 'ftp://%s' % proxyServer
  1265.             internetSettings.Close()
  1266.         except (WindowsError, ValueError, TypeError):
  1267.             # Either registry key not found etc, or the value in an
  1268.             # unexpected format.
  1269.             # proxies already set up to be empty so nothing to do
  1270.             pass
  1271.         return proxies
  1272.  
  1273.     def getproxies():
  1274.         """Return a dictionary of scheme -> proxy server URL mappings.
  1275.  
  1276.         Returns settings gathered from the environment, if specified,
  1277.         or the registry.
  1278.  
  1279.         """
  1280.         return getproxies_environment() or getproxies_registry()
  1281.  
  1282.     def proxy_bypass(host):
  1283.         try:
  1284.             import _winreg
  1285.             import re
  1286.         except ImportError:
  1287.             # Std modules, so should be around - but you never know!
  1288.             return 0
  1289.         try:
  1290.             internetSettings = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,
  1291.                 r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
  1292.             proxyEnable = _winreg.QueryValueEx(internetSettings,
  1293.                                                'ProxyEnable')[0]
  1294.             proxyOverride = str(_winreg.QueryValueEx(internetSettings,
  1295.                                                      'ProxyOverride')[0])
  1296.             # ^^^^ Returned as Unicode but problems if not converted to ASCII
  1297.         except WindowsError:
  1298.             return 0
  1299.         if not proxyEnable or not proxyOverride:
  1300.             return 0
  1301.         # try to make a host list from name and IP address.
  1302.         host = [host]
  1303.         try:
  1304.             addr = socket.gethostbyname(host[0])
  1305.             if addr != host:
  1306.                 host.append(addr)
  1307.         except socket.error:
  1308.             pass
  1309.         # make a check value list from the registry entry: replace the
  1310.         # '<local>' string by the localhost entry and the corresponding
  1311.         # canonical entry.
  1312.         proxyOverride = proxyOverride.split(';')
  1313.         i = 0
  1314.         while i < len(proxyOverride):
  1315.             if proxyOverride[i] == '<local>':
  1316.                 proxyOverride[i:i+1] = ['localhost',
  1317.                                         '127.0.0.1',
  1318.                                         socket.gethostname(),
  1319.                                         socket.gethostbyname(
  1320.                                             socket.gethostname())]
  1321.             i += 1
  1322.         # print proxyOverride
  1323.         # now check if we match one of the registry values.
  1324.         for test in proxyOverride:
  1325.             test = test.replace(".", r"\.")     # mask dots
  1326.             test = test.replace("*", r".*")     # change glob sequence
  1327.             test = test.replace("?", r".")      # change glob char
  1328.             for val in host:
  1329.                 # print "%s <--> %s" %( test, val )
  1330.                 if re.match(test, val, re.I):
  1331.                     return 1
  1332.         return 0
  1333.  
  1334. else:
  1335.     # By default use environment variables
  1336.     getproxies = getproxies_environment
  1337.  
  1338.     def proxy_bypass(host):
  1339.         return 0
  1340.  
  1341. # Test and time quote() and unquote()
  1342. def test1():
  1343.     s = ''
  1344.     for i in range(256): s = s + chr(i)
  1345.     s = s*4
  1346.     t0 = time.time()
  1347.     qs = quote(s)
  1348.     uqs = unquote(qs)
  1349.     t1 = time.time()
  1350.     if uqs != s:
  1351.         print 'Wrong!'
  1352.     print repr(s)
  1353.     print repr(qs)
  1354.     print repr(uqs)
  1355.     print round(t1 - t0, 3), 'sec'
  1356.  
  1357.  
  1358. def reporthook(blocknum, blocksize, totalsize):
  1359.     # Report during remote transfers
  1360.     print "Block number: %d, Block size: %d, Total size: %d" % (
  1361.         blocknum, blocksize, totalsize)
  1362.  
  1363. # Test program
  1364. def test(args=[]):
  1365.     if not args:
  1366.         args = [
  1367.             '/etc/passwd',
  1368.             'file:/etc/passwd',
  1369.             'file://localhost/etc/passwd',
  1370.             'ftp://ftp.python.org/pub/python/README',
  1371. ##          'gopher://gopher.micro.umn.edu/1/',
  1372.             'http://www.python.org/index.html',
  1373.             ]
  1374.         if hasattr(URLopener, "open_https"):
  1375.             args.append('https://synergy.as.cmu.edu/~geek/')
  1376.     try:
  1377.         for url in args:
  1378.             print '-'*10, url, '-'*10
  1379.             fn, h = urlretrieve(url, None, reporthook)
  1380.             print fn
  1381.             if h:
  1382.                 print '======'
  1383.                 for k in h.keys(): print k + ':', h[k]
  1384.                 print '======'
  1385.             fp = open(fn, 'rb')
  1386.             data = fp.read()
  1387.             del fp
  1388.             if '\r' in data:
  1389.                 table = string.maketrans("", "")
  1390.                 data = data.translate(table, "\r")
  1391.             print data
  1392.             fn, h = None, None
  1393.         print '-'*40
  1394.     finally:
  1395.         urlcleanup()
  1396.  
  1397. def main():
  1398.     import getopt, sys
  1399.     try:
  1400.         opts, args = getopt.getopt(sys.argv[1:], "th")
  1401.     except getopt.error, msg:
  1402.         print msg
  1403.         print "Use -h for help"
  1404.         return
  1405.     t = 0
  1406.     for o, a in opts:
  1407.         if o == '-t':
  1408.             t = t + 1
  1409.         if o == '-h':
  1410.             print "Usage: python urllib.py [-t] [url ...]"
  1411.             print "-t runs self-test;",
  1412.             print "otherwise, contents of urls are printed"
  1413.             return
  1414.     if t:
  1415.         if t > 1:
  1416.             test1()
  1417.         test(args)
  1418.     else:
  1419.         if not args:
  1420.             print "Use -h for help"
  1421.         for url in args:
  1422.             print urlopen(url).read(),
  1423.  
  1424. # Run test program when run as a script
  1425. if __name__ == '__main__':
  1426.     main()
  1427.